<?php

namespace app\admin\service\common\permission;


use app\common\Constants;
use think\facade\Log;

class MinDataPermissionResolver
{
    private const PRIORITY_MAP = [
        Constants::DATA_SCOPE_ALL => 6,
        Constants::DATA_SCOPE_DEPT_CUSTOM => 5,
        Constants::DATA_SCOPE_DEPT_AND_SUB => 4,
        Constants::DATA_SCOPE_DEPT_CURRENT => 3,
        Constants::DATA_SCOPE_SELF => 2,
        Constants::DATA_SCOPE_NONE => 1
    ];
    public function resolve(array $permissions): array
    {
        trace('min data permission resolution start', 'debug');

        if (empty($permissions)) {
            return [
                'type' => 'NONE',
                'custom_dept_ids' => [],
                'priority' => self::PRIORITY_MAP['NONE']
            ];
        }

        $lowestPriority = PHP_INT_MAX;
        $selectedPermission = null;
        $customDeptIds = [];

        foreach ($permissions as $perm) {
            $priority = self::PRIORITY_MAP[$perm['type']] ?? PHP_INT_MAX;

            // 收集所有自定义权限的有效部门ID
            if ($perm['type'] === 'DEPT_CUSTOM' && !empty($perm['custom_dept_ids'])) {
                $validIds = array_filter($perm['custom_dept_ids'], function ($id) {
                    return $id !== null && $id !== '';
                });
                $customDeptIds = array_merge($customDeptIds, $validIds);
            }

            // 选择最低优先级权限
            if ($priority < $lowestPriority) {
                $lowestPriority = $priority;
                $selectedPermission = $perm;
            }
        }

        // 处理合并后的部门ID
        $mergedDeptIds = [];
        if (!empty($customDeptIds)) {
            $mergedDeptIds = array_values(array_unique($customDeptIds));
        }

        trace('The strategy for permission resolution is based on the principle of minimization');

        return [
            'type' => $selectedPermission['type'],
            'custom_dept_ids' => $mergedDeptIds,
            'priority' => $lowestPriority
        ];
    }
}